<?php


namespace app\shop\controller;

use app\Controller;
use app\model\system\User as UserModel;
use app\model\web\Config as ConfigModel;
use app\model\web\WebSite as WebsiteModel;
use app\Request;
use think\captcha\facade\Captcha as ThinkCaptcha;
use think\facade\Cache;
use think\facade\Config;
use app\model\system\Site;
use think\facade\Db;
use think\facade\Log;

/**
 * 登录
 * Class Login
 * @package app\shop\controller
 */
class Login extends Controller
{

    protected $app_module = "shop";

    protected $hll_url = "https://openapi.huolala.cn/v1";

    protected $hll_app_key = "2gvx7jOMdh4eBruYiwXds5wXntxgvEdv";

    /**
     * 登录首页
     * @return mixed
     */
    public function login()
    {
        $site_id      = request()->siteid();
        $config_model = new ConfigModel();
        $config_info  = $config_model->getCaptchaConfig();
        $config       = $config_info['data']['value'];
        $this->assign('shop_login', $config['shop_login']);
        if (request()->isAjax()) {
            $username   = input("username", '');
            $password   = input("password", '');
            $user_model = new UserModel();
            if ($config["shop_login"] == 1) {
                $captcha_result = $this->checkCaptcha();
                //验证码
                if ($captcha_result["code"] != 0) {
                    return $captcha_result;
                }
            }
            $result = $user_model->login($username, $password, $this->app_module, $site_id);
            return $result;
        } else {
            $this->assign("menu_info", ['title' => "登录"]);
            //平台配置信息
            $site_model = new Site();
            $shop_info  = $site_model->getSiteInfo([['site_id', '=', $site_id]], 'site_name,logo,seo_keywords,seo_description, create_time');

            $this->assign("shop_info", $shop_info['data']);
            $this->assign('domain', $_SERVER['SERVER_NAME']);

            //加载版权信息
            $copyright = $config_model->getCopyright();
            $this->assign('copyright', $copyright['data']['value']);

            // 验证码
            $captcha = $this->captcha();
            $captcha = $captcha['data'];
            $this->assign('site_id', $site_id);
            $this->assign("captcha", $captcha);
            return $this->fetch("login/login");
        }
    }

    /**
     * 退出操作
     */
    public function logout()
    {
        $site_id    = request()->siteid();
        $user_model = new UserModel();
        $user_model->clearLogin($this->app_module, $site_id);
        $this->redirect(url("shop/login/login"));
    }

    /**
     * 验证码
     */
    public function captcha()
    {
        $captcha_data = ThinkCaptcha::create(null, true);
        $captcha_id   = md5(uniqid(null, true));
        // 验证码10分钟有效
        Cache::set($captcha_id, $captcha_data['code'], 600);
        return success(0, '', ['id' => $captcha_id, 'img' => $captcha_data['img']]);
    }

    /**
     * 验证码验证
     */
    public function checkCaptcha()
    {
        $captcha    = input('captcha', '');
        $captcha_id = input('captcha_id', '');

        if (empty($captcha)) return error(-1, '请输入验证码');

        $captcha_data = Cache::pull($captcha_id);
        if (empty($captcha_data)) return error('', '验证码已失效');

        if ($captcha != $captcha_data) return error(-1, '验证码错误');

        return success();
    }

    /**
     * 清理缓存
     */
    public function clearCache()
    {
        Cache::clear();
        return success('', '缓存更新成功', '');
    }

    /**
     * 修改密码
     * */
    public function modifyPassword()
    {
        if (request()->isAjax()) {
            $site_id    = request()->siteid();
            $user_model = new UserModel();
            $uid        = $user_model->uid($this->app_module, $site_id);
            $old_pass = input('old_pass', '');
            $new_pass = input('new_pass', '123456');
            $condition = [
                ['uid', '=', $uid],
                ['password', '=', data_md5($old_pass)],
                ['site_id', '=', $site_id]
            ];
            $res = $user_model->modifyAdminUserPassword($condition, $new_pass);
            return $res;
        }
    }

    // 根据order_goods_id输出发货人和收货人的坐标
    private function get_lat_lon($order_goods_id)
    {
        $f_address = $this->poi_search(1, $order_goods_id);
        $s_address = $this->poi_search(2, $order_goods_id);
        $lat_lon_arr = [
            ['lat' => $f_address['location']['lat'], 'lon' => $f_address['location']['lon'], 'city_id' => $f_address['city_id']],
            ['lat' => $s_address['location']['lat'], 'lon' => $s_address['location']['lon'], 'city_id' => $s_address['city_id']],
        ];
        $lat_lon_arr = json_encode($lat_lon_arr);
        return $lat_lon_arr;
    }

    //获取发货人收货人全中文地址
    private function get_address($order_goods_id)
    {
        $order_goods = Db::name('order_goods')->where('order_goods_id', $order_goods_id)->find();
        //检索发货人
        $f_user = Db::name('user')->find($order_goods['offer_member']);
        $f_p_name = Db::name('area')->where('id', $f_user['province_id'])->value('name');
        $f_c_name = Db::name('area')->where('id', $f_user['city_id'])->value('name');
        $f_d_name = Db::name('area')->where('id', $f_user['district_id'])->value('name');
        $f_full_address = $f_p_name.$f_c_name.$f_d_name.$f_user['address'];
        //检索收货人(从订单获取)
        $s_user = Db::name('order')->where('order_id', $order_goods['order_id'])->find();
        $s_p_name = Db::name('area')->where('id', $s_user['province_id'])->value('name');
        $s_c_name = Db::name('area')->where('id', $s_user['city_id'])->value('name');
        $s_d_name = Db::name('area')->where('id', $s_user['district_id'])->value('name');
        $s_full_address = $s_p_name.$s_c_name.$s_d_name.$s_user['address'];
        return [$f_full_address, $s_full_address];
    }

    //获取已开通城市列表
    public function city_list($order_goods_id)
    {
        $data = [
            'api_method'    =>  'e-city-list',
            'api_version'   =>  '1.0',
            'app_key'       =>  $this->hll_app_key,
            'nonce_str'     =>  rand(0, 10000000),
            'timestamp'     =>  time(),
        ];
        $data['signature'] = $this->signature($data);
        $return = $this->h_api($this->hll_url, $data);
        $return = json_decode($return, true);
        $return['all_address'] = $this->get_address($order_goods_id);
        return json($return);
    }

    // 获取可选车型及增值服务(城市下)
    public function city_info()
    {
        //获取下单人城市ID
        $order_goods_id = input('order_goods_id');
        $city_id = $this->get_city_id(1, $order_goods_id);
        $data = [
            'api_method'    =>  'e-city-info',
            'api_version'   =>  '1.0',
            'app_key'       =>  $this->hll_app_key,
            'nonce_str'     =>  rand(0, 10000000),
            'timestamp'     =>  time(),
            'city_id'       =>  $city_id,
        ];
        $data['signature'] = $this->signature($data);
        $return = $this->h_api($this->hll_url, $data);
        return $return;
    }
    
    //获取发送人和下单人信息
    public function get_info()
    {
        $order_goods_id = input('order_goods_id');
        $address = $this->get_address($order_goods_id);
        //订单信息
        $order_goods = Db::name('order_goods')->where('order_goods_id', $order_goods_id)->find();
        //发货人信息
        $f_user = Db::name('user')->where('uid', $order_goods['offer_member'])->find();
        //收货人信息(从订单获取)
        $s_user = Db::name('order')->where('order_id', $order_goods['order_id'])->find();
        $data = [
            'f_name'    =>  $f_user['offer_person'],
            'f_mobile'  =>  $f_user['offer_mobile'],
            'f_address' =>  $address[0],
            
            's_name'    =>  $s_user['name'],
            's_mobile'  =>  $s_user['mobile'],
            's_address' =>  $address[1],
            
        ];
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    }
    
    // 获取下单人城市版本号
    public function get_revision($order_goods_id)
    {
        //获取下单人城市ID
        $city_id = $this->get_city_id(1, $order_goods_id);
        $data = [
            'api_method'    =>  'e-city-info',
            'api_version'   =>  '1.0',
            'app_key'       =>  $this->hll_app_key,
            'nonce_str'     =>  rand(0, 10000000),
            'timestamp'     =>  time(),
            'city_id'       =>  $city_id,
        ];
        $data['signature'] = $this->signature($data);
        $return = $this->h_api($this->hll_url, $data);
        $return = json_decode($return, true);
        return $return['data']['revision'];
    }

    // 地址检索
    public function poi_search($type, $order_goods_id)
    {
        $order_goods = Db::name('order_goods')->where('order_goods_id', $order_goods_id)->find();
        //检索发货人
        if ($type == 1){
            $f_user = Db::name('user')->find($order_goods['offer_member']);
            $p_name = Db::name('area')->where('id', $f_user['province_id'])->value('name');
            $c_name = Db::name('area')->where('id', $f_user['city_id'])->value('name');
            $d_name = Db::name('area')->where('id', $f_user['district_id'])->value('name');
            $full_address = $p_name.$c_name.$d_name.$f_user['address'];
        }else{
            //检索收货人(从订单获取)
            $s_user = Db::name('order')->where('order_id', $order_goods['order_id'])->find();
            $p_name = Db::name('area')->where('id', $s_user['province_id'])->value('name');
            $c_name = Db::name('area')->where('id', $s_user['city_id'])->value('name');
            $d_name = Db::name('area')->where('id', $s_user['district_id'])->value('name');
            $full_address = $p_name.$c_name.$d_name.$s_user['address'];
        }
        $data = [
            'api_method'    =>  'e-city-search',
            'api_version'   =>  '1.0',
            'app_key'       =>  $this->hll_app_key,
            'nonce_str'     =>  rand(0, 10000000),
            'timestamp'     =>  time(),
            'kw'            =>  $full_address,
        ];
        $data['signature'] = $this->signature($data);
        $return = $this->h_api($this->hll_url, $data);
        $return = json_decode($return, true);
        return $return['data']['poi'][1];
    }

    
    // 获取城市ID
    public function get_city_id($type, $order_goods_id)
    {
        $order_goods = Db::name('order_goods')->where('order_goods_id', $order_goods_id)->find();
        //检索发货人
        if ($type == 1){
            $f_user = Db::name('user')->find($order_goods['offer_member']);
            $p_name = Db::name('area')->where('id', $f_user['province_id'])->value('name');
            $c_name = Db::name('area')->where('id', $f_user['city_id'])->value('name');
            $d_name = Db::name('area')->where('id', $f_user['district_id'])->value('name');
            $full_address = $p_name.$c_name.$d_name.$f_user['address'];
        }else{
            //检索收货人(从订单获取)
            $s_user = Db::name('order')->where('order_id', $order_goods['order_id'])->find();
            $p_name = Db::name('area')->where('id', $s_user['province_id'])->value('name');
            $c_name = Db::name('area')->where('id', $s_user['city_id'])->value('name');
            $d_name = Db::name('area')->where('id', $s_user['district_id'])->value('name');
            $full_address = $p_name.$c_name.$d_name.$s_user['address'];
        }
        $data = [
            'api_method'    =>  'e-city-search',
            'api_version'   =>  '1.0',
            'app_key'       =>  $this->hll_app_key,
            'nonce_str'     =>  rand(0, 10000000),
            'timestamp'     =>  time(),
            'kw'            =>  $full_address,
        ];
        $data['signature'] = $this->signature($data);
        $return = $this->h_api($this->hll_url, $data);
        $return = json_decode($return, true);
        return $return['data']['poi'][1]['city_id'];
    }

    //货拉拉计价
    public function order_price_calculate()
    {
        //获取下单人城市ID
        $order_goods_id = input('order_goods_id');
        $city_id = $this->get_city_id(1, $order_goods_id);

        $data = [
            'api_method'        =>  'e-price-calculate',
            'api_version'       =>  '1.0',
            'app_key'           =>  $this->hll_app_key,
            'access_token'      =>  config('token.access_token'),
            'timestamp'         =>  time(),
            'nonce_str'         =>  strval(rand(0, 10000000)),
            // 下单城市id
            'city_id'           =>  strval($city_id),
            // 下单车型ID
            'order_vehicle_id'  =>  input('order_vehicle_id'),
            // 车型附加要求
            'std_tag_arr'       =>  '[]',
            // 订单额外服务
            'spec_req_arr'      =>  '[]',
            // 当前最新城市版本号
            'city_info_revision'=>  $this->get_revision($order_goods_id),
            // 发货地和收货地经纬度数据列表
            'lat_lon_arr'       =>  $this->get_lat_lon($order_goods_id),
        ];
        $data['signature'] = $this->signature($data);
//        Log::error($data['signature']);
        $return = $this->h_api($this->hll_url, $data);
        return $return;
    }

    // 下单
    public function order_request()
    {
        $order_goods_id = input('order_goods_id');
        //发货人POI
        $f_addr = $this->poi_search(1, $order_goods_id);
        //收货人POI
        $s_addr = $this->poi_search(2, $order_goods_id);

        //订单信息
        $order_goods = Db::name('order_goods')->where('order_goods_id', $order_goods_id)->find();
        
        //发货人信息
        $f_user = Db::name('user')->where('uid', $order_goods['offer_member'])->find();
        
        //收货人信息
        $s_user = Db::name('order')->where('order_id', $order_goods['order_id'])->find();

        $addr_info = [
            // 发货地址资料
            [
                'name' => $f_addr['name'],
                'addr' => $f_addr['address'],
                'lat_lon' => $f_addr['location'],
                'city_id' => $f_addr['city_id'],
                'district_name' =>  $f_addr['area'],
                'contact_name' =>   $f_user['offer_person'],
                'contact_phone_no' => $f_user['offer_mobile'],
            ],
            // 收货地址资料
            [
                'name' => $s_addr['name'],
                'addr' => $s_addr['address'],
                'lat_lon' => $s_addr['location'],
                'city_id' => $s_addr['city_id'],
                'district_name' =>  $s_addr['area'],
                'contact_name' =>   $s_user['name'],
                'contact_phone_no' => $s_user['mobile'],
            ]
        ];
        $addr_info = json_encode($addr_info);

        $data = [
            'api_method' => 'e-order-request',
            'api_version' => '1.0',
            'access_token' => config('token.access_token'),
            'app_key' => $this->hll_app_key,
            'nonce_str' => rand(0, 10000000),
            'timestamp' => time(),
            // 下单城市id
            'city_id' => $f_addr['city_id'],
            // 下单车型ID
            'order_vehicle_id' => input('order_vehicle_id'),
            // 订单额外服务
            'spec_req_arr' => '[]',
            // 发/收货地poi数据列表
            'addr_info' => $addr_info,
            //用车时间
            'order_time' => time(),
            //订单总金额
            'total_price_fen' => input('total_price_fen'),
            //当前最新的城市版本号
            'city_info_revision' => $this->get_revision($order_goods_id),
            //下单联系人
            'contact_name' => $f_user['offer_person'],
            //下单联系手机
            'contact_phone_no' => $f_user['offer_mobile'],
            //下单支付方式，3：余额支付，8：月结账户支付(不能与其他支付方式混用)；
            'pay_type' => 3,
        ];
        $data['signature'] = $this->signature($data);
        $return = $this->h_api($this->hll_url, $data);
        $result = json_decode($return, true);
        if ($result['ret'] == 0){
            $hll_order_id = $result['data']['order_display_id'];
            if (!empty($hll_order_id)){
				//查询$order_goods
				$order_goods = Db::name('order_goods')->where('order_goods_id', $order_goods_id)->find();
				//查询本笔订单该供应商的所有商品
				$order_goods_id_arr = Db::name('order_goods')->where([
					'order_id'     => $order_goods['order_id'],
					'offer_member' => $order_goods['offer_member'],
				])->column('order_goods_id');
                //批量更新货拉拉订单号
                Db::name('order_goods')->whereIn('order_goods_id', $order_goods_id_arr)->update([
                    'hll'          =>  $hll_order_id,
                ]);
            }
        }
        return $return;
    }

    //货拉拉订单取消
    public function order_cancel()
    {
        $order_goods_id = input('order_goods_id');
        $order_goods = Db::name('order_goods')->where('order_goods_id', $order_goods_id)->find();
        $data = [
            'api_method' => 'e-order-cancel',
            'api_version' => '1.0',
            'app_key' => $this->hll_app_key,
            'access_token' => config('token.access_token'),
            'timestamp' => time(),
            'nonce_str' => rand(0, 10000000),
            // 货拉拉订单号
            'order_display_id' => $order_goods['hll'],
        ];
        $data['signature'] = $this->signature($data);
        $return = $this->h_api($this->hll_url, $data);
        $result = json_decode($return, true);
        if ($result['ret'] == 0 || $result['ret'] == 10009){
			//查询$order_goods
			$order_goods = Db::name('order_goods')->where('order_goods_id', $order_goods_id)->find();
			//查询本笔订单该供应商的所有商品
			$order_goods_id_arr = Db::name('order_goods')->where([
				'order_id'     => $order_goods['order_id'],
				'offer_member' => $order_goods['offer_member'],
			])->column('order_goods_id');
            // 清空商品的货拉拉订单号
            Db::name('order_goods')->whereIn('order_goods_id', $order_goods_id_arr)->update(['hll' => '']);
        }
        return $return;
    }

    //货拉拉订单详情
    private function order_detail($order_display_id)
    {
        $data = [
            'api_method'        =>  'e-order-detail',
            'api_version'       =>  '1.0',
            'app_key'           =>  $this->hll_app_key,
            'access_token'      =>  config('token.access_token'),
            'timestamp'         =>  time(),
            'nonce_str'         =>  rand(0, 10000000),
            // 订单号
            'order_display_id'  =>  $order_display_id,
        ];
        $data['signature'] = $this->signature($data);
        $return = $this->h_api($this->hll_url, $data);
        $result = json_decode($return, true);
        return $result;
    }

    public function auth(Request $request)
    {
        $url = $request->domain().'/shop/login/callback';
        return $this->redirect('https://open.huolala.cn/#/oauth/authorize?response_type=code&client_id='.$this->hll_app_key.'&redirect_uri='.$url.'&auth_mobile=13667820371');
    }

    public function callback()
    {
        $code = input('code');
        if (empty($code)){
            return '授权code为空';
        }
        $data = file_get_contents('https://open.huolala.cn/oauth/token?grant_type=authorization_code&client_id='.$this->hll_app_key.'&code='.$code);
        $data = json_decode($data, true);
        Log::error($data);
        if ($data['ret'] == 0){
            Config::set([
                'access_token'  => $data['data']['access_token'],
                'refresh_token' => $data['data']['refresh_token'],
                'auth_end_time' => $data['data']['auth_end_time'],
            ], 'token');
            return '授权成功，接口三个月后需重新授权，access_token：'.$data['data']['access_token'].'，refresh_token：'.$data['data']['refresh_token'].'，预计下次授权时间：'.$data['data']['auth_end_time'];
        }
        return '授权失败：'.$data['msg'];
    }

    /**
     * 货拉拉司机信息定时更新
     */
    public function hll_task()
    {
        //找出所有未获取到司机信息的单子
        $data = Db::name('order_goods')->where([['hll', '<>', 0], ['hll', '<>', '']])->field('order_goods_id,hll')->select();
        if (!empty($data)){
            foreach ($data as $k => $v){
                //查询订单，获得司机信息
                $driver_info = $this->order_detail($v['hll']);
//                halt($driver_info);
                if (!empty($driver_info['data']['driver_info'])){
                    Db::name('order_goods')->where('order_goods_id', $v['order_goods_id'])->update([
                        'hll_name'           =>  $driver_info['name'],
                        'hll_phone_no'       =>  $driver_info['phone_no'],
                        'hll_license_plate'  =>  $driver_info['license_plate'],
                    ]);
                }
            }
            return count($data->toArray());
        }
        return 0;
    }
    
    //批量获取货拉拉订单
    public function get_orders()
    {
        $data = [
            'api_method'        =>  'e-order-list',
            'api_version'       =>  '1.0',
            'app_key'           =>  $this->hll_app_key,
            'access_token'      =>  config('token.access_token'),
            'timestamp'         =>  time(),
            'nonce_str'         =>  rand(0, 10000000),
        ];
        $data['signature'] = $this->signature($data);
        $return = $this->h_api($this->hll_url, $data);
        $result = json_decode($return, true);
        return $result;
    }
    
    //测试
    public function test()
    {
        return $this->get_lat_lon(662);
    }
}